package cn.sundat.web.action;
/**
 * 企业注册登录action
 * author LeeLiang
 */

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import cn.sundat.model.Company;
import cn.sundat.model.PageBean;
import cn.sundat.model.Profile;
import cn.sundat.service.CompanyService;
import cn.sundat.service.ProfileService;
import cn.sundat.utils.FastJsonUtil;
import cn.sundat.utils.MailUtil;
import cn.sundat.utils.QrcodeUtil;
import cn.sundat.utils.UploadUtils;


public class CompanyAction extends ActionSupport{
	
	private static Map<String, String> map = new HashMap<String, String>();
	@Resource(name="companyService")
	private CompanyService companyService;
	@Resource(name="profileService")
	private ProfileService profileService;
	
	/**
	 * ognl封装两个类的对象的属性
	 */
	private Company company = new Company();
	private Profile profile = new Profile();
	
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
	public Profile getProfile() {
		return profile;
	}
	public void setProfile(Profile profile) {
		this.profile = profile;
	}
	
	/**
	 * 属性封装文件对象
	 */
	private File[] 	 upload;
	private String[] uploadFileName;
	private String[] uploadContentType;
	
	public void setUpload(File[] upload) {
		this.upload = upload;
	}
	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
	/**
	 * 属性封装
	 */
	private Integer currPage=1;
	private Integer pageSize=10;
	
	
	public void setCurrPage(Integer currPage) {
		if(currPage==null) {
			currPage=1;
		}
		this.currPage = currPage;
	}
	public void setPageSize(Integer pageSize) {
		if(pageSize==null) {
			pageSize=2;
		}
		this.pageSize = pageSize;
	}
	/**
	 * 注册方法
	 * @return
	 * @throws IOException 
	 */
	public String register() throws IOException {
		//验证表单有没有重复提交
		String c_lingpai = ServletActionContext.getRequest().getParameter("c_lingpai");
		String s_lingpai = (String) ActionContext.getContext().getSession().get("s_lingpai");
		System.out.println(c_lingpai+s_lingpai);
		if(s_lingpai==null || !s_lingpai.equals(c_lingpai)) {
			return "registerok";
		}
		//清除本次注册session
		ActionContext.getContext().getSession().remove("s_lingpai");
		
		//为保证图片的安全性，放到WEB-INF目录下
		String path = ServletActionContext.getServletContext().getRealPath("/upload/companyinfo");
		File file = new File(path);
		if(!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
		String file3 = ServletActionContext.getRequest().getParameter("file3");
		String file4 = ServletActionContext.getRequest().getParameter("file4");
		String file5 = ServletActionContext.getRequest().getParameter("file5");
		String file6 = ServletActionContext.getRequest().getParameter("file6");
		String file7 = ServletActionContext.getRequest().getParameter("file7");
		System.out.println("file4;"+file4+"file5:"+file5+"file6"+file6+"file7"+file7);
		//存储荣誉证书的名字
		Set<String> set =null;
		if(file7.trim().length()>0) {
			set = new HashSet<String>();
		}
		//每个公司每个文件夹
		String companyPath = UploadUtils.getCompanyPath(company.getComp_name());
		File saveFile = new File(file,companyPath);
		if(!saveFile.exists() && !saveFile.isDirectory()) {
			saveFile.mkdir();
		}
		
		if(uploadFileName!=null && uploadFileName.length>0) {
			int n = upload.length;
			System.out.println("==============================:"+n);
			boolean flag2 = true,flag3=true,flag4=true,flag5 = true;
			for(int i=0;i<n;i++) {
				//文件
				File img = upload[i];
				//文件名字
				String name = uploadFileName[i];
				//随机名字
				String uuidName = UploadUtils.getUUIDName(name);
				
				//图片复制
				FileUtils.copyFile(img, new File(saveFile, uuidName));
				//封装数据，往数据库写入
				switch (i) {
					case 0:
						profile.setPro_license(companyPath+File.separator+uuidName);
						System.out.println("1图片");
					break;
					case 1:
						profile.setPro_requisition(companyPath+File.separator+uuidName);	
						System.out.println("2图片");
					break;
					case 2:
						if(file3.trim().length()>0 && flag2==true) {
							profile.setPro_ratepaying(companyPath+File.separator+uuidName);
							flag2=false;
							System.out.println("3图片");
							break;
						}
					case 3:
						if(file4.trim().length()>0 && flag3==true) {
							profile.setPro_aptitude(companyPath+File.separator+uuidName);
							flag3=false;
							System.out.println("4图片");
							break;
						}
					case 4:
						//如果file5为空则跳过去
						if(file5.trim().length()>0 && flag4==true) {
							profile.setPro_NoCrime(companyPath+File.separator+uuidName);
							flag4=false;
							System.out.println("5图片");
							break;
						}
					case 5:
						//如果file6为空则不设置
						if(file6.trim().length()>0 && flag5==true) {
							profile.setPro_prove(companyPath+File.separator+uuidName);	
							flag5=false;
							System.out.println("6图片");
							break;
						}
					default:
						//如果file7为空则不设置
						if(file7.trim().length()>0) {
							set.add(companyPath+File.separator+uuidName);
							profile.setPro_honor(set.toString().substring(1,set.toString().length()-1));
							System.out.println("7图片");
						}
						break;
				}
				company.setComp_state(0);
				company.setProfile(profile);
				company.setComp_level(4);
			}
			
		}
		String uuidName = UploadUtils.getUUIDName(company.getComp_name());
		profile.setPro_qrcode(companyPath+File.separator+uuidName+".png");
		companyService.save(company);
		Long getComp_id = companyService.getByName(company.getComp_name()).getComp_id();
		HttpServletRequest request = ServletActionContext.getRequest();
		String content=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/company_findById?company.comp_id="+getComp_id;
		QrcodeUtil.createQrcode(saveFile.getAbsolutePath()+File.separator+uuidName+".png", content);//生成页面二维码
		
		return "registerok";
	}
	
	/**
	 * 检测方法,根据公司名称或者代码检测
	 * @return 状态码为0，表示未注册
	 * 		       状态码为1 表示注册但未验证中 
	 * 		      状态码为2表示可以登录
	 * @throws IOException 
	 * @throws ServletException 
	 */
	public String checkLogin() throws IOException, ServletException {
		int loginState = companyService.checkLogin(company.getComp_name(),company.getComp_pwd());
		ServletActionContext.getResponse().getWriter().print(loginState);
		return NONE;
	}
	
	/**
	 * 登录方法
	 * @return
	 */
	public String login() {
		List<Company> list = companyService.login(company.getComp_name(),company.getComp_pwd());
		
		if(list.size()>0) {
			ServletActionContext.getRequest().getSession().setAttribute("comp", list.get(0));
			return "loginok";
		}else {
			
		}
		
		return NONE;
	}
	
	/**
	 * 注销登录的公司账号
	 * @throws IOException 
	 */
	public String logout() throws IOException {
		//销毁session
		ServletActionContext.getRequest().getSession().invalidate();
		//页面重定向
		ServletActionContext.getResponse().sendRedirect(ServletActionContext.getRequest().getContextPath());
		return NONE;
	}
	
	/**
	 * 公司信息修改,修改时先将修改的数据和以前数据封装
	 * 然后插入到表中，状态码设置为3，当审核通过就删掉状态为1的，将这一条状态设置为1
	 * @return
	 * @throws IOException 
	 */
	public String update() throws IOException {
		Company oldCompany = companyService.getById(company.getComp_id());
		Profile oldProfile = profileService.getById(profile.getPro_id());
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");

		System.out.println("上传来的"+profile);
		if(uploadFileName!=null && uploadFileName.length>0) {
		//需要审核的save
			//设置修改处没有的信息
			company.setComp_pwd(oldCompany.getComp_pwd());
			company.setComp_level(oldCompany.getComp_level());
			company.setComp_state(3);
			
			profile.setPro_requisition(oldProfile.getPro_requisition());//入会申请
			profile.setPro_ratepaying(oldProfile.getPro_ratepaying());//纳税证明
			profile.setPro_aptitude(oldProfile.getPro_aptitude());//企业资质
			profile.setPro_NoCrime(oldProfile.getPro_NoCrime());//无犯罪证明
			profile.setPro_prove(oldProfile.getPro_prove());//其他证书
			profile.setPro_honor(oldProfile.getPro_honor());//荣誉证书
			
			String realPath = ServletActionContext.getServletContext().getRealPath("/upload/companyinfo");
			File file = new File(realPath);
			//本公司的文件夹名称
			String companyPath = UploadUtils.getCompanyPath(oldCompany.getComp_name());
			//公司文件存取地址
			File companyFile = new File(file,companyPath);
			for (File f : upload) {
				String uuidName = UploadUtils.getUUIDName(uploadFileName[0]);
				FileUtils.copyFile(f, new File(companyFile, uuidName));
				
				//设置给数据库字段
				profile.setPro_license(companyPath+File.separator+uuidName);
			}
			
			//3 置空company和profile的id
			company.setComp_id(null);
			profile.setPro_id(null);
			//4 封装完成要修改的数据
			company.setProfile(profile);
			//5 调用service完成保存
			companyService.save(company);
			ServletActionContext.getResponse().getWriter().print("修改成功，等待审核。");
			
		}else {
		//不需要审核的update
			//电话，邮箱，经营范围，公司简介可能发生变化
			oldProfile.setPro_phone(profile.getPro_phone());
			oldCompany.setComp_name(company.getComp_name());
			oldProfile.setPro_email(profile.getPro_email());
			oldProfile.setPro_scope(profile.getPro_scope());
			oldProfile.setPro_intro(profile.getPro_intro());
			
			//调用service更新
			companyService.update(oldCompany);
			//写回浏览器
			ServletActionContext.getResponse().getWriter().print("修改成功，重修登录生效。");
		}
		
		return NONE;
	}
	
	/**
	 * 忘记公司之发送邮件
	 * @return
	 * @throws Exception 
	 */
	public String findPWD() throws Exception {
		//获取邮箱
		Company c = companyService.getByName(company.getComp_name());
		//随机获取一个六位数字
		String str = String.valueOf((int)((Math.random()*9+1)*100000));
		map.put("code", str);
		MailUtil.sendMail(c.getProfile().getPro_email(), str);
		return NONE;
	}
	
	/**
	 * 验证邮箱/根据id  修改密码
	 * @throws IOException 
	 */
//	public String resetpwd() throws IOException {
//		//判断验证码是否合适
//		String code = ServletActionContext.getRequest().getParameter("code");
//		if(code==null) {
//			Company c = companyService.getById(company.getComp_id());
//			String oldpwd = ServletActionContext.getRequest().getParameter("oldpwd");
//			System.out.println("原密码"+c);
//			System.out.println("x的"+company);
//			//根据公司名字修改密码
//			if(c.getComp_pwd().equals(oldpwd)) {
//				//旧密码正确
//				c.setComp_pwd(company.getComp_pwd());
//				companyService.update(c);
//				ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
//				ServletActionContext.getResponse().getWriter().print("修改成功");
//			}else {
//				//旧密码不正确
//				ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
//				ServletActionContext.getResponse().getWriter().print("旧密码错误");
//			}
//		}else {
//			//根据邮箱验证码修改密码
//			if(map.get("code").equals(code)) {
//				//调用service层修改密码
//				Company c = companyService.getByName(company.getComp_name());
//				c.setComp_pwd(company.getComp_pwd());
//				companyService.update(c);
//			}else {
//				//验证码错误
//				ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
//				ServletActionContext.getResponse().getWriter().print("验证码错误");
//			}
//		}
//		
//		return NONE;
//	}
	public String resetpwd() throws IOException {
		//判断验证码是否合适
		String code = ServletActionContext.getRequest().getParameter("code");
		if(code==null) {
			Company c = companyService.getById(company.getComp_id());
			String oldpwd = ServletActionContext.getRequest().getParameter("oldpwd");
			System.out.println("原密码"+c);
			System.out.println("x的"+company);
			//根据公司名字修改密码
			if(c.getComp_pwd().equals(oldpwd)) {
				//旧密码正确
				c.setComp_pwd(company.getComp_pwd());
				companyService.update(c);
				ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print("修改成功");
			}else {
				//旧密码不正确
				ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print("旧密码错误");
			}
		}else {
			//根据邮箱验证码修改密码
			if(map.get("code").equals(code)) {
				//调用service层修改密码
				Company c = companyService.getByName(company.getComp_name());
				c.setComp_pwd(company.getComp_pwd());
				companyService.update(c);
			}else {
				//验证码错误
				ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print("验证码错误");
			}
		}
		
		return NONE;
	}

	
	/**
	 * 根据公司名字获取公司的邮箱
	 * @return
	 * @throws IOException 
	 */
	public String findByName() throws IOException {
		Company c =  companyService.getByName(company.getComp_name());
		if(c!=null) {
			String pro_email = c.getProfile().getPro_email();
			System.out.println(pro_email);
			ServletActionContext.getResponse().getWriter().print(pro_email);
		}else {
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			ServletActionContext.getResponse().getWriter().print("没有该公司注册信息");
		}
		return NONE;
	}
	
	/**
	 * 根据公司的会员等级搜索公司
	 * @return
	 */
	public String findByLevel() {
		Integer pageSize = 10;
		HttpServletRequest request = ServletActionContext.getRequest();
		 int currPage = Integer.parseInt(request.getParameter("currPage"));
		 int level = Integer.parseInt(request.getParameter("level"));
		PageBean<Company> pb =  companyService.findByLevel(currPage,pageSize,level);
		ServletActionContext.getRequest().setAttribute("pb", pb);
		return "huiyuan";
	}
	
	/**
	 * 查询单个
	 * @return
	 */
	public String findById() {
		Long comp_id = company.getComp_id();
		Company company =  companyService.findById(comp_id);
		ServletActionContext.getRequest().setAttribute("company", company);
		return "xiangqing";
	}
	
	/**
	 * 根据名字模糊查询
	 * @return 一个pagebean对象
	 * @throws IOException 
	 */
	public String findPbByName() throws IOException {
		String comp_name = company.getComp_name();
		System.out.println("名字"+comp_name);
		System.out.println("当前页等"+currPage+"jkj"+pageSize);
		DetachedCriteria criteria = DetachedCriteria.forClass(Company.class);
		criteria.add(Restrictions.like("comp_name", "%"+comp_name+"%"));
		PageBean<Company> pb = companyService.findPbByName(currPage,pageSize,criteria);
		System.out.println("这是pagebean对象"+pb.getBeanlist().size());
		ServletActionContext.getRequest().setAttribute("pb", pb);
		ServletActionContext.getRequest().setAttribute("comp_name", comp_name);
		return "searchresult";
	}
	/**
	 * 等级升级
	 * @return
	 * @throws IOException 
	 */
	public String upLevel() throws IOException {
		String realPath = ServletActionContext.getServletContext().getRealPath("/upload/companyinfo");
		File file = new File(realPath);
		Company oldCompany = companyService.getById(company.getComp_id());
		//把图片保存下来到该公司的文件夹中
		String filePath = UploadUtils.getCompanyPath(oldCompany.getComp_name());
		File companyFile = new File(file, filePath);
		if(!companyFile.exists() && !companyFile.isDirectory()) {
			companyFile.mkdir();
		}
		
		String UUIDName =  UploadUtils.getUUIDName(uploadFileName[0]);
		FileUtils.copyFile(upload[0], new File(companyFile, UUIDName));
		//数据库中写入一条数据，状态改为待审核状态，等审核的时候将图片的位置改掉就可以了
		oldCompany.getProfile().setPro_uplevel(filePath+File.separator+UUIDName);
		//调用service修改
		companyService.update(oldCompany);
		return "uplevel";
	}
}




